package com.example.dataservice.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.dataservice.entity.Competition;
import com.example.dataservice.service.impl.CompetitionServiceImpl;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Component
@RabbitListener(queuesToDeclare = @Queue(name = "person",durable = "false"))//durable持久化，除此外@Queue注解还可以配置其他参数
public class DirectQueueConsumer {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CompetitionServiceImpl competitionService;
    private static final String COMPETITION_KEY="competition";
    @RabbitListener(queuesToDeclare = @Queue("club_queue"))
    public void receive1(String msg){
        System.out.println("queue接收到消息direct message: "+msg);
        Long id = Long.parseLong(msg);

        List<String> list = stringRedisTemplate.opsForList().range(COMPETITION_KEY, 0, -1);
        Gson gson =new Gson();
        assert list != null;
        List<String> collect = list.stream().map(item -> {
            Competition competition = gson.fromJson(item, Competition.class);
            if (Objects.equals(competition.getId(), id)) {
                LambdaQueryWrapper<Competition> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Competition::getId, id);
                Competition one = competitionService.getOne(queryWrapper);
                return gson.toJson(one);
            } else {
                return item;
            }
        }).collect(Collectors.toList());
        stringRedisTemplate.opsForList().leftPushAll(COMPETITION_KEY, collect);
    }

}

